# _*_ coding：UTF-8 _*_
# @Time：2021/9/414:34
# @Author：JYZ
# @Project：oneWork

import urllib.request
import urllib.parse

# cname: 长沙
# pid:
# pageIndex: 1
# pageSize: 10

# 创建请求地址 自定义爬取请求函数
def create_quest(page):
    url = "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname"

    data = {
        "cname": "长沙",
        "pid":"",
        "pageIndex": page,
        "pageSize": "10"
        }

    data = urllib.parse.urlencode(data).encode("utf-8")

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'}

    # 请求对象定制
    requests = urllib.request.Request(url=url, headers=headers,data=data)
    return requests

# 获取请求内容
def getRequestData(requests):
    # 获取响应数据
    response = urllib.request.urlopen(requests)
    # 数据解码
    content = response.read().decode("utf-8")
    return content

# 下载方法
def downLoad(content, page):
    page = str(page)
    # 默认使用GBK 编码 若内容中有中文 使用 encoding="utf-8" 编码格式
    fp = open("KFC_" + page + ".json", "w", encoding="utf-8")
    fp.write(content)
    fp.close()


start_page = input("请输入起始页：")
end_page = input("请输入结束页：")
start = int(start_page)
end = int(end_page)
for page in range(start, end + 1):
    request = create_quest(page)
    content = getRequestData(request)
    downLoad(content, page)
